﻿namespace Resharper.Abstractions.CodeDom.TypeMembers.Indexers
{
  using System;
  using JetBrains.Annotations;
  using JetBrains.ReSharper.Psi.CSharp.Tree;
  using JetBrains.ReSharper.Psi.Tree;
  using Resharper.Abstractions.Actions;
  using Resharper.Abstractions.CodeDom.TreeNodes;
  using Resharper.Abstractions.CodeDom.TypeMembers.Fields.Constants;

  /// <summary>Defines the <see cref="ConstantExtensions"/> class.</summary>
  public static class IndexerExtensions
  {
    #region Public Methods

    /// <summary>Gets the containing property.</summary>
    /// <param name="context">The context.</param>
    /// <returns>Returns the containing property.</returns>
    /// <exception cref="System.ArgumentNullException">context</exception>
    public static Indexer GetContainingIndexer([NotNull] this ProviderContext context)
    {
      if (context == null)
      {
        throw new ArgumentNullException("context");
      }

      var result = context.InternalGetSelectedElement<IIndexerDeclaration>();

      return result != null ? new Indexer(result) : null;
    }

    /// <summary>Gets the property.</summary>
    /// <param name="treeNode">The tree node.</param>
    /// <returns>Returns the property.</returns>
    public static Indexer GetIndexer([NotNull] this TreeNode treeNode)
    {
      var indexer = treeNode.InternalTreeNode as IIndexerDeclaration;

      return indexer != null ? new Indexer(indexer) : null;
    }

    /// <summary>Creates the constant.</summary>
    /// <param name="context">The context.</param>
    /// <returns>Returns the constant.</returns>
    public static Indexer GetSelectedIndexer([NotNull] this ProviderContext context)
    {
      if (context == null)
      {
        throw new ArgumentNullException("context");
      }

      var result = context.InternalGetSelectedElement<IIndexerDeclaration>();
      if (result == null)
      {
        return null;
      }

      var selectedTreeNode = context.GetSelectedTreeNode();
      if (selectedTreeNode == null)
      {
        return null;
      }

      if (!result.GetNameDocumentRange().Contains(selectedTreeNode.GetDocumentRange()))
      {
        return null;
      }

      return new Indexer(result);
    }

    #endregion
  }
}